﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace XdXdBot.Console
{
    using Console = System.Console;

    class Program
    {
        static void Main(string[] args)
        {
            if (!HttpListener.IsSupported)
            {
                Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
                return;
            }

            HttpListener listener = new HttpListener();
            listener.Prefixes.Add("http://+:8080/");
            listener.Start();
            listener.BeginGetContext(Handle, listener);
            Console.ReadLine();
        }

        private static void Handle(IAsyncResult ar)
        {
            var listener = ar.AsyncState as HttpListener;
            if (listener.IsListening is false)
                return;
            Console.WriteLine("我们发现了一个Push!");
            HttpListenerContext context = listener.EndGetContext(ar);
            using (var json = new StreamReader(context.Request.InputStream))
            {

                var text = json.ReadToEnd();
                Root giteepush = JsonConvert.DeserializeObject<Root>(text);
                Console.WriteLine($"仓库:{giteepush.repository.full_name}");
                giteepush.commits.ForEach(x =>
                {
                    Console.WriteLine($"Commit:{x.message}");
                    Console.WriteLine(x.author.name);
                });
                Console.WriteLine($"Push时间{DateTime.FromFileTime(long.Parse(giteepush.timestamp))}");

            }
            listener.BeginGetContext(Handle, listener);


        }

    }
}
